package pt.biblioescala

import java.sql.{Connection, DriverManager, ResultSet};

object DBController {
  
  classOf[com.mysql.jdbc.Driver]
  private val conn: Connection = DriverManager.getConnection("jdbc:mysql://localhost/biblioescala?user=root&password=root")
  
  def newStudent(student: Student)
  {
	  ControlSQL.update(conn, "INSERT INTO student VALUES(" + student + ", 0)")
  }
  
  // Checks if the student already exists
  def getStudent(year: Int, classNumber: Char, number: Int) : String =
  {
	  val students = ControlSQL.queryEach(conn,
		  			"SELECT * FROM student WHERE year=" + year + " AND classNumber='" + classNumber + "' AND number=" + number + " LIMIT 1")
	  {
	    rs => rs.getString("name")
	  }
	  if(students.length > 0)
	    students(0)
	  else
	    null
  }
 
  // Register new entry
  def newStudentEntry(studentid: Int, entrytypeID : Int)
  {
    ControlSQL.update(conn, "INSERT INTO studententry (studentid, entrytypeid) VALUES (" + studentid + ", " + entrytypeID + ")");
  }
  
  def newEntryType(entryType: String)
  {
    ControlSQL.update(conn, "INSERT INTO entrytype (designation) VALUES ('" + entryType + "')");
  }
  
  def getEntryTypes() : List[String] =
  {
	  ControlSQL.queryEach(conn, "SELECT * FROM entrytype")
	  {
	    rs => rs.getString("designation")
	  }
  }
}